const namespace = "[HINT]";
const now = new Date();
const nowtime = `${now.toLocaleDateString()} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
const timestamp = now.getTime();

const hintLogPath = "hint.log";
const groovyHintSource =
  "http://ms-dev.hancode.com/paas/api/system/naked/api-list";
const groovyHintPath = "src/hint/groovy.js";
// TODO
// const javascriptHintOutput = "src/hint/javascript.js";

let axios, fs, chalk, jsonformat;
try {
  axios = require("axios");
  fs = require("fs-extra");
  chalk = require("chalk");
  jsonformat = require("json-format");
  run();
} catch (err) {
  Promise.all([
    import("axios"),
    import("fs-extra"),
    import("chalk"),
    import("json-format"),
  ]).then((res) => {
    axios = res[0].default;
    fs = res[1].default;
    chalk = res[2].default;
    jsonformat = res[3].default;
    run();
  });
}

async function run() {
  let flag = false;

  if (process.argv[2] === "--force") {
    // 强制执行
    flag = true;
  } else if (fs.existsSync(hintLogPath)) {
    // 存在日志文件
    const data = fs.readFileSync(hintLogPath).toString();
    const result = data.match(/\[Timestamp\]\s(\d{13})/);
    if (!result) {
      // 未匹配、认为低版本
      flag = true;
    } else {
      // 根据时间决定是否执行
      const delta = timestamp - Number(result[1]);
      flag = delta > 24 * 60 * 40 * 1000;
    }
  } else {
    // 首次
    flag = true;
  }

  if (flag) {
    await loadGroovyHint();
    const logContext = [`[Time] "${nowtime}"`, `[Timestamp] ${timestamp}`].join(
      "\n"
    );
    fs.ensureFileSync(hintLogPath);
    fs.writeFileSync(hintLogPath, logContext);
  } else {
    const message = [
      chalk.red(namespace),
      chalk.green(`Skiped.`),
      chalk.green(`Enforce it with`),
      chalk.yellow("npm run hint -- --force"),
      chalk.green(`if nessesary.`),
    ];
    console.log(...message, "\n");
  }
}

async function loadGroovyHint() {
  let { data: response } = await axios.get(groovyHintSource);
  const { data } = response;

  const fileContent = [
    "/**",
    ` * Toatal: ${data.length} items`,
    " */",
    `export default ${jsonformat(data, { type: "space", size: 2 })}`,
  ].join("\n");

  fs.ensureFileSync(groovyHintPath);
  fs.writeFileSync(groovyHintPath, fileContent);

  const message = [
    chalk.red(namespace),
    chalk.green(`Update`),
    chalk.yellow(`${groovyHintPath}`),
    chalk.green(`Successfully.`),
  ];
  console.log(...message, "\n");
}
